package com.ncmmall.mall.controller.business.marketing;

import com.ncmmall.application.business.coupon.CouponApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.marketing.coupon.Coupon;
import com.ncmmall.domain.business.marketing.coupon.CouponChannel;
import com.ncmmall.domain.business.marketing.coupon.CouponGoods;
import com.ncmmall.domain.business.marketing.coupon.QCoupon;
import com.ncmmall.domain.business.marketing.coupon.QCouponChannel;
import com.ncmmall.domain.business.marketing.coupon.QCouponGoods;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.QMerchantGoodsChannel;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 优惠券管理
 *
 * @author linxs
 * @date: 2019-07-10 17:44
 */
@Controller
@RequestMapping(value = "/mall/coupon")
@Slf4j
public class CouponController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private CouponApplication couponApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 优惠券列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, Coupon coupon) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select u from Coupon u where 1=1 ", params, coupon);
        QueryPage<Coupon> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Coupon.class);

        model.addAttribute("page", page).addAttribute("params", coupon);

        return "mall/marketing/coupon/list";
    }


    /**
     * 查看详情
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {
        List<GoodsChannel> channels = queryChannelService.findAll(QGoodsChannel.goodsChannel.parent.isNull(), GoodsChannel.class);
        List<String> channelNames = queryChannelService.findAll(QCouponChannel.couponChannel.coupon.id.eq(id), CouponChannel.class).stream().map(input -> input.getChannel().getName()).collect(Collectors.toList());
        List<CouponGoods> goodses = queryChannelService.findAll(QCouponGoods.couponGoods.coupon.id.eq(id), CouponGoods.class);
        model.addAttribute("_method", "PUT").addAttribute("coupon", queryChannelService.findOne(QCoupon.coupon.id.eq(id), Coupon.class)).addAttribute("channels", channels).addAttribute("goodses", goodses).addAttribute("channelNames", channelNames);
        return "mall/marketing/coupon/detail";
    }

    /**
     * 审核页面
     */
    @RequestMapping(value = "/{id}/process", method = RequestMethod.GET)
    private String process(Model model, @PathVariable("id") long id) {
        List<GoodsChannel> channels = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(Securitys.currentUser().getId()), MerchantGoodsChannel.class).stream().map(MerchantGoodsChannel::getChannel).collect(Collectors.toList());
        List<String> channelNames = queryChannelService.findAll(QCouponChannel.couponChannel.coupon.id.eq(id), CouponChannel.class).stream().map(input -> input.getChannel().getName()).collect(Collectors.toList());
        List<CouponGoods> goodses = queryChannelService.findAll(QCouponGoods.couponGoods.coupon.id.eq(id), CouponGoods.class);
        model.addAttribute("_method", "PUT").addAttribute("coupon", queryChannelService.findOne(QCoupon.coupon.id.eq(id), Coupon.class)).addAttribute("channels", channels).addAttribute("goodses", goodses).addAttribute("channelNames", channelNames);
        return "mall/marketing/coupon/process";
    }

    /**
     * 审核优惠券
     */
    @RequestMapping(value = "/{id}/process", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> process(HttpServletRequest request, Coupon params) {
        try {
            couponApplication.process(params);
            logApplication.eventOfSystem(Securitys.currentUser(), "审核优惠券" + params.getName(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[优惠券审核异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 设置精选优惠券
     */
    @RequestMapping(value = "/{id}/choice", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> choice(HttpServletRequest request, Coupon params) {
        try {
            couponApplication.choice(params);
            logApplication.eventOfSystem(Securitys.currentUser(), "设置优惠券为精选优惠券", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[优惠券审核异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 取消精选优惠券
     */
    @RequestMapping(value = "/{id}/cancelChoice", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> cancelChoice(HttpServletRequest request, Coupon params) {
        try {
            couponApplication.cancelChoice(params);
            logApplication.eventOfSystem(Securitys.currentUser(), "取消精选优惠券", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[优惠券审核异常]", e);
            return ImmutableMap.of("status", false);
        }
    }


    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Coupon coupon) {

        if (StringUtils.isNotBlank(coupon.getName())) {
            sql += " and u.name like :name";
            params.put("name", "%" + coupon.getName() + "%");
        }

        if (coupon.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", coupon.getStatus());
        } else {
            sql += " and u.status > 1 ";
        }

        if (coupon.getType() > 0) {
            sql += " and u.type = :type";
            params.put("type", coupon.getType());
        }

        sql += " order by u.createTime desc";

        return sql;
    }

}
